package com.ruhaly.sandianke;

import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;

import com.blankj.utilcode.utils.ToastUtils;
import com.ruhaly.common_lib.base.BaseActivity;
import com.ruhaly.common_lib.utils.Utils;
import com.ruhaly.sandianke.data.DataModelFactory;
import com.ruhaly.sandianke.databinding.ActivityWebViewBinding;
import com.ruhaly.sandianke.viewmodel.WebViewViewModel;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebBackForwardList;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;


public class WebViewActivity extends BaseActivity<ActivityWebViewBinding> {
    WebViewViewModel viewModel;

    RxPermissions rxPermissions;
    static final String URL = "http://www.sandianke.com/b2b2c/tour";
//    static final String URL = "http://www.mapleage.com/b2b2c/tour";

    @Override
    public void initTitleFrame() {


    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_web_view;
    }

    @Override
    public void initView(Bundle savedInstanceState) {

        initVM();
       /*以下控件设置*/

        initWebViewSettings();
        rxPermissions = new RxPermissions(this);

        rxPermissions
                .request(android.Manifest.permission.ACCESS_FINE_LOCATION,
                        android.Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) { // 在android 6.0之前会默认返回true
                    } else {
                        ToastUtils.showShortToast("请打开相应的权限");
                        finish();
                    }
                });
    }

    public void initVM() {
        viewModel = initVM(WebViewViewModel.class);
        getB().setViewModel(viewModel);
    }

    @Override
    public void setStatusBar() {
        setTranslucentForImageViewInFragment(this, null);
    }

    public void initWebViewSettings() {
        getB().webview.setWebChromeClient(new MyWebChromeClient());
        getB().webview.loadUrl(URL);
        //js调用java
        getB().webview.addJavascriptInterface(new JsInteration(), "bridgeAnd");
    }

    private long exitTime = 0;

    public void closeView() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            showToast("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    class JsInteration {

        @JavascriptInterface
        public void getLoc() {
            getLocation();
        }

        @JavascriptInterface
        public void share(String url, String title, String imgUrl, String content) {
            shareSNS(url, title, content, imgUrl);
        }

        @JavascriptInterface
        public void wxAuth() {
            weChatAuth(null);
        }
    }

    public void getLocation() {
        rxPermissions
                .request(android.Manifest.permission.ACCESS_FINE_LOCATION,
                        android.Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) { // 在android 6.0之前会默认返回true
                        // 已经获取权限
                        requestLoc();
                    } else {
                        ToastUtils.showShortToast("请打开定位权限");
                    }
                });
    }

    public void notifyHTMLLoc(String lnt, String lat) {
        getB().webview.loadUrl("javascript:getLocation('" + lnt + "','" + lat + "')");
    }

    public String currentCity = "";

    public void requestLoc() {
        DataModelFactory.getInstance().getLocationInfo().getBdLocation(this, TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA).subscribe(location -> {


            if (!TextUtils.isEmpty(location.getCity()) && !currentCity.equals(location.getCity())) {
                currentCity = location.getCity();
                Utils.snack(this, "当前城市" + currentCity);
                double lnt = location.getLongitude();
                double lat = location.getLatitude();
                notifyHTMLLoc(String.valueOf(lnt), String.valueOf(lat));
            }

        }, throwable -> handleThrowable(throwable));
    }

    class MyWebChromeClient extends WebChromeClient {

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }

        //扩展浏览器上传文件
        //3.0++版本
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooserImpl(uploadMsg);
        }

        //3.0--版本
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooserImpl(uploadMsg);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android > 5.0
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> uploadMsg, WebChromeClient.FileChooserParams fileChooserParams) {
            openFileChooserImplForAndroid5(uploadMsg);
            return true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 10) {
            getB().webview.reload();
        } else if (requestCode == 101) {
//            web_view.loadUrl("javascript:getAddressData()");
        } else if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            if (data == null || resultCode != RESULT_OK || null == data.getData()) {
                return;
            }
//            String path = ImageUtils.getRealPathFromUri(getBaseContext(), data.getData());
//            Luban.get(this)
//                    .load(new File(path))                     //传人要压缩的图片
//                    .putGear(Luban.THIRD_GEAR)      //设定压缩档次，默认三挡
//                    .setCompressListener(new OnCompressListener() { //设置回调
//
//                        @Override
//                        public void onStart() {
//                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
//                        }
//
//                        @Override
//                        public void onSuccess(File file) {
//                            // TODO 压缩成功后调用，返回压缩后的图片文件
//
//                            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//                            //转成url
//                            Uri result = Uri.parse(MediaStore.Images.Media.insertImage(
//                                    getContentResolver(), bitmap, null, null));
//                            mUploadMessage.onReceiveValue(result);
//                            mUploadMessage = null;
//                        }
//
//                        @Override
//                        public void onError(Throwable e) {
//                            // TODO 当压缩过去出现问题时调用
//                        }
//                    }).launch();    //启动压缩
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;

        } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            if (null == mUploadMessageForAndroid5)
                return;

            if (data == null || resultCode != RESULT_OK || null == data.getData()) {
                return;
            }
//            String path = ImageUtils.getRealPathFromUri(getBaseContext(), data.getData());
//            Luban.get(this)
//                    .load(new File(path))                     //传人要压缩的图片
//                    .putGear(Luban.THIRD_GEAR)      //设定压缩档次，默认三挡
//                    .setCompressListener(new OnCompressListener() { //设置回调
//
//                        @Override
//                        public void onStart() {
//                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
//                        }
//
//                        @Override
//                        public void onSuccess(File file) {
//                            // TODO 压缩成功后调用，返回压缩后的图片文件
//
//                            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//                            //转成url
//                            Uri result = Uri.parse(MediaStore.Images.Media.insertImage(
//                                    getContentResolver(), bitmap, null, null));
//                            if (result != null) {
//                                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
//                            } else {
//                                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
//                            }
//                            mUploadMessageForAndroid5 = null;
//                        }
//
//                        @Override
//                        public void onError(Throwable e) {
//                            // TODO 当压缩过去出现问题时调用
//                        }
//                    }).launch();    //启动压缩
//

            Uri result = (data == null || resultCode != RESULT_OK) ? null : data.getData();
            if (result != null) {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
            } else {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
            }
            mUploadMessageForAndroid5 = null;
        }
    }

    protected String getAbsoluteImagePath(Uri uri) {
        // can post image
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, proj, // Which columns to return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)

        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
    }

    public ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> mUploadMessageForAndroid5;

    public final static int FILECHOOSER_RESULTCODE = 1;
    public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 2;

    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
    }

    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
        mUploadMessageForAndroid5 = uploadMsg;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");

        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
    }

    class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (getB().webview.canGoBack() && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                //获取历史列表
                WebBackForwardList mWebBackForwardList = getB().webview.copyBackForwardList();
                //判断当前历史列表是否最顶端,其实canGoBack已经判断过
                if (mWebBackForwardList.getCurrentIndex() > 1) {
                    getB().webview.goBack();
                    return true;
                } else {
                    closeView();
                }
            } else {
                closeView();
            }

            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void finish() {
        SDKApplication.getIns().exitApp();
    }

    UMShareAPI mShareAPI;

    public void weChatAuth(View view) {
        doQQWXOauthVerify(SHARE_MEDIA.WEIXIN);
    }

    public void doQQWXOauthVerify(final SHARE_MEDIA platform) {
        if (null == mShareAPI) {
            mShareAPI = UMShareAPI.get(WebViewActivity.this);
        }
        mShareAPI.deleteOauth(WebViewActivity.this, platform, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {

            }
        });
        boolean isInstall = mShareAPI.isInstall(this, platform);
        if (platform == SHARE_MEDIA.WEIXIN && !isInstall) {
            showToast("请先安装最新版本的微信客户端");
            return;
        }
        if (true) {
            mShareAPI.doOauthVerify(WebViewActivity.this, platform, new UMAuthListener() {
                @Override
                public void onStart(SHARE_MEDIA share_media) {

                }

                @Override
                public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                    getQQWXInfo(platform);
                }

                @Override
                public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                    showToast(throwable.getMessage());
                }

                @Override
                public void onCancel(SHARE_MEDIA share_media, int i) {

                }
            });
        } else {
            getQQWXInfo(platform);
        }
    }

    public void getQQWXInfo(final SHARE_MEDIA platform) {
        mShareAPI.getPlatformInfo(WebViewActivity.this, platform, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

                getB().webview.loadUrl("javascript:bindingWeixin('" + map.get("openid") + "','" + map.get("name") + "')");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                showToast(throwable.getMessage());
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
            }
        });
    }

}
